<template>
    <view class="content bg_com">
        <scroll-view class="msg_scroll"
                     scroll-y="true"
                     :scroll-top="msgScrollTop">
            <view :class="{ 'detail-item': true , 'detail-mine' : item.isMineFlag}"
                  v-for="(item,index) in detailMsgSession.msgs"
                  :key="index">
                <!-- <view class="time">07-09 17:12</view> -->
                <div class="detail-content">
                    <image class="user-icon"
                           :src='item.isMineFlag ? item.mine.avatar: item.other.avatar '></image>
                    <view class="msg">
                        {{item.text}}
                    </view>
                </div>
            </view>
        </scroll-view>
        <view class="sendBox">
            <input type="text"
                   placeholder="请输入..."
                   placeholder-style="color:#E5DDFF"
                   v-model="p2pVal"
                   @confirm="sendP2PMsg">
            <button class="sendBtn"
                    @click="sendP2PMsg">发送</button>
        </view>
    </view>
</template>

<script>
import {
    mapState
} from 'vuex';
import NIM from '../../../house/libs/NIM_Web_NIM_miniapp_v8.9.0'
// const appKey = '9bbedb58f17bba7bbf3256f43c8cab91' //云信appKey
let nimInstance
export default {
    computed: mapState(['hasLogin', 'user', 'identity', 'tickets']),
    data() {
        return {
            p2pMsgArr: [],
            msgScrollTop: 0,
            detailMsgSession: [],
            p2pVal: '',
            msgItemData: {},
        }
    },
    onShow() {
        console.log('onshow')

    },
    onLoad(option) {
        console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>', option.item)
        this.msgItemData = option.item && JSON.parse(option.item)
        console.log('>>>>>>>>>>>>>>>>>>>>>>>>>>>>', this.msgItemData)
        uni.setNavigationBarTitle({ title: this.msgItemData.nick })
        this.initNIM()
    },
    methods: {
        //初始化云信账号
        initNIM() {
            const {
                uid,
                netEaseToken
            } = this.identity;
            var _nim = NIM.getInstance({
                debug: false, // 是否开启日志，将其打印到console。集成开发阶段建议打开。
                appKey: this.$urlConfig.appKey,
                account: uid,
                token: netEaseToken,
                db: true, //若不要开启数据库请设置false。SDK默认为true。
                onsessions: async (sessions) => {

                    // const p2pTextMsgs = sessions.filter(ele => ele.scene == 'p2p' && ele.lastMsg.type == 'text');
                    // console.log('sessions', p2pTextMsgs)
                    // for (let i in p2pTextMsgs) {
                    //     await this.$api.userDetail({
                    //         uid: this.identity.uid,
                    //         ticket: this.tickets[0].ticket,
                    //         targetUid: sessions[i].to,

                    //     }).then((res) => {
                    //         p2pTextMsgs[i].avatar = res.data.avatar;
                    //         p2pTextMsgs[i].nick = res.data.nick;
                    //     })
                    // }
                    // this.p2pMsgArr = p2pTextMsgs;
                },
                onupdatesession: (session) => {
                    console.log('updatesession', session)
                    // this.$set(this.p2pMsgArr, this.p2pMsgArr.findIndex(i => i.to == session.to), {
                    //     ...this.p2pMsgArr.find(i => i.to == session.to),
                    //     ...session,
                    // })
                    if (session.lastMsg.from != this.identity.uid) {
                        if (this.detailMsgSession && this.detailMsgSession.msgs) {
                            this.detailMsgSession.msgs.push({
                                ...session.lastMsg,
                                mine: this.user,
                                other: this.detailMsgSession.other,
                                isMineFlag: false,
                            })
                            //滚动到底部
                        }
                        this.msgScrollTop += 80
                    }

                },
            });
            nimInstance = _nim;
            this.handleIntoMsgDetail(this.msgItemData)

        },
        timesub(time) {
            var date = new Date(time);
            var year = date.getFullYear();
            var mou = date.getMonth() + 1;
            var day = date.getDate();
            var hours = date.getHours();
            var minutes = date.getMinutes();
            var myDate = new Date();
            var newdate = (myDate.getMonth() * 30) + myDate.getDate();
            var thisdate = (mou * 30) + day;
            hours < 10 ? hours = '0' + hours : null;
            minutes < 10 ? minutes = '0' + minutes : null;
            day < 10 ? day = '0' + day : null;
            mou < 10 ? mou = '0' + mou : null;
            if (myDate.getFullYear() != year) {
                var newtime = year + '-' + mou + '-' + day + ' ' + hours + ':' + minutes;
            } else if (newdate - thisdate > 2) {
                var newtime = mou + '-' + day + ' ' + hours + ':' + minutes;
            } else if (newdate - thisdate == 2) {
                var newtime = '前天 ' + hours + ':' + minutes;
            } else if (newdate - thisdate == 1) {
                var newtime = '昨天 ' + hours + ':' + minutes;
            } else {
                var newtime = hours + ':' + minutes;
            }
            return newtime;
        },

        handleIntoMsgDetail(item) { //聊天详情
            nimInstance.setCurrSession(item.id)
            //滚动到底部
            nimInstance.getHistoryMsgs({
                scene: 'p2p',
                to: item.to,
                reverse: true,
                done: (err, obj) => {
                    console.log('获取具体聊天记录', obj, obj.msgs)
                    this.detailMsgSession = {
                        ...obj,
                        mine: this.user,
                        other: item,
                        msgs: obj.msgs.map(msg => {
                            return {
                                ...msg,
                                mine: this.user,
                                other: item,
                                isMineFlag: msg.from == this.user.uid
                            }
                        }),
                        _item: item
                    }
                    uni.hideTabBar()
                    this.open();
                    setTimeout(() => {
                        this.msgScrollTop = this.detailMsgSession.msgs.length * 80;
                    }, 500);

                }
            });
        },
        open() {
            this.$refs.popupP2pMsgs.open();
        },
        close() {
            this.$refs.popupP2pMsgs.close();
        },
        sendP2PMsg() {
            nimInstance.sendText({
                scene: 'p2p',
                to: this.detailMsgSession.other.to,
                text: this.p2pVal,
                done: (error, msg) => {
                    //滚动到底部
                    this.p2pVal = ''
                    this.detailMsgSession.msgs.push({
                        ...msg,
                        mine: this.user,
                        other: this.detailMsgSession.other,
                        isMineFlag: true,
                    })
                    this.msgScrollTop += 80
                }
            });
        },
        handBackToP2PList() {
            console.log(this.detailMsgSession)
            nimInstance.resetCurrSession()
            this.detailMsgSession = {},
                this.close();
            uni.showTabBar();
        },
    },
    onHide() {
        console.log('onhide')
        nimInstance && nimInstance.destroy()
    }
}
</script>

<style lang="scss">
.msg_scroll {
    background: rgba($color: #181526, $alpha: 0.9);
    box-sizing: border-box;
    position: relative;
    height: 100vh;
    width: 100%;
    font-family: PingFang SC;
    font-weight: 500;
    color: #f1edff;
    padding: 0 31rpx;
}
.detail-tip {
    height: 92rpx;
    line-height: 92rpx;
    font-size: 34rpx;
    position: relative;
    color: #f1edff;
    text-align: center;
    margin-bottom: 30rpx;
    image {
        width: 44rpx;
        height: 44rpx;
        position: absolute;
        left: 0;
        top: 0;
        bottom: 0;
        margin: auto;
    }
}
.detail-item {
    margin-bottom: 40rpx;
    .time {
        text-align: center;
        font-size: 20rpx;
        color: #ccc;
        margin-bottom: 26rpx;
    }
    .detail-content {
        display: flex;

        .user-icon {
            width: 80rpx;
            height: 80rpx;
            border-radius: 50%;
            margin-right: 24rpx;
        }
        .msg {
            //    width: 480rpx;
            display: inline-block;
            padding: 24rpx;
            font-size: 28rpx;
            border-radius: 4rpx 24rpx 24rpx 24rpx;
            background: rgba($color: #e5ddff, $alpha: 0.1);
            margin: 0 24rpx;
            word-wrap: break-word;
            word-break: break-all;
            white-space: pre-line;
        }
    }
}
.detail-mine {
    .detail-content {
        flex-direction: row-reverse;
        .msg {
            background: rgba($color: #3dfff2, $alpha: 0.2);
            border-radius: 24rpx 4rpx 24rpx 24rpx;
        }
    }
}
.sendBox {
    width: 750rpx;
    height: 98rpx;
    background: #252138;
    position: absolute;
    bottom: 0;
    left: 0;
    display: flex;
    justify-content: center;
    align-items: center;
    // position: relative;
    input {
        width: 600rpx;
        height: 76rpx;
        background: rgba($color: #e5ddff, $alpha: 0.05);
        color: #fff;
        border-radius: 38rpx;
        padding: 0 30rpx;
        font-size: 24rpx;
    }
    .sendBtn {
        width: 120rpx;
        height: 56rpx;
        background: linear-gradient(90deg, #0ea793 0%, #0877ae 82%);
        border-radius: 28rpx;
        position: absolute;
        font-size: 24rpx;
        color: #fff;
        line-height: 24rpx;
        right: 54rpx;
        bottom: 0;
        top: 0;
        margin: auto;
        display: flex;
        justify-content: center;
        align-items: center;
        z-index: 3;
    }
}
</style>
